import click
import sys, argparse, traceback, importlib
from flask.cli import with_appcontext


# @app.cli.command()
# @click.argument("name")
# @click.option('--count', help='Number of greetings.')
# def print_user(count, name):
#     # args = sys.argv[2:]
#     # parser = argparse.ArgumentParser(add_help=True)
#     # parser.add_argument("-m", "--name", dest="name", metavar="name", help="指定job名", required=True)
#     # params = parser.parse_args(args)
#     # params_dict = params.__dict__
#     # print(params_dict)
#     print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", count, name)


@click.command()
@with_appcontext
@click.option('-m', help='Number of greetings.')
@click.option('-a', help='Number of greetings.')
@click.option('-p', help='Number of greetings.')
def runjob(m, *args, **kwargs):
    args = sys.argv[2:]
    parser = argparse.ArgumentParser(add_help=True)
    parser.add_argument("-m", dest="name", metavar="name", help="指定job名", required=True)
    parser.add_argument("-a", dest="act", metavar="act", help="job动作", required=False)
    parser.add_argument("-p", dest="param", metavar="param", help="业务参数", required=False)
    params = parser.parse_args(args)
    params_dict = params.__dict__
    if "name" not in params_dict or not params_dict["name"]:
        print("请输入调用文件")
    try:
        """
        from jobs.tasks.test import JobTask
        """
        module_name = params_dict["name"].replace("/", ".")
        import_string = "jobs.tasks.%s" % (module_name)
        target = importlib.import_module(import_string)
        exit(target.JobTask().run(params_dict))
    except Exception as e:
        traceback.print_exc()
        print(params_dict)
        print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", m)
